package recolhalixo;

import java.util.Collection;
import java.util.Map;

import jadex.commons.SimplePropertyObject;
import jadex.extension.envsupport.environment.IEnvironmentSpace;
import jadex.extension.envsupport.environment.ISpaceAction;
import jadex.extension.envsupport.environment.ISpaceObject;
import jadex.extension.envsupport.environment.RoundBasedExecutor;
import jadex.extension.envsupport.environment.space2d.Grid2D;
import jadex.extension.envsupport.environment.space2d.Space2D;
import jadex.extension.envsupport.math.IVector2;
import jadex.extension.envsupport.math.Vector1Int;
import jadex.extension.envsupport.math.Vector2Int;

public class AccaoMover extends SimplePropertyObject implements ISpaceAction {
	
	public static final String CIMA="u";
	public static final String BAIXO="d";
	public static final String ESQUERDA="l";
	public static final String DIREITA="r";
	
	public static final String DIRECCAO="dir";

	@Override
	public Object perform(Map parameters, IEnvironmentSpace space) {
		String dir = (String)parameters.get(DIRECCAO);
		Object oid = parameters.get(ISpaceAction.OBJECT_ID);
		ISpaceObject obj = space.getSpaceObject(oid);
		IVector2 pos = (IVector2)obj.getProperty(Space2D.PROPERTY_POSITION);
		
		int px = pos.getXAsInteger();
		int py = pos.getYAsInteger();
		
		if (dir.equals(CIMA)) {py=py-1;}
		else if (dir.equals(BAIXO)) {py=py+1;}
		else if (dir.equals(ESQUERDA)) {px=px-1;}
		else if (dir.equals(DIREITA)) {px=px+1;}
		
		IVector2 newPos = new Vector2Int(px,py);
		if (walkable(newPos, space)) {
			Collection estradasActuais = ((Grid2D) space).getSpaceObjectsByGridPosition(pos, "estrada");
			
			if (estradasActuais==null
				|| ((String)((ISpaceObject)estradasActuais.iterator().next()).getProperty("direction")).contains(dir)) {
					((Space2D)space).setPosition(oid, newPos);
					obj.setProperty("ultimo_movimento", dir);
					obj.setProperty("distance", (Integer)obj.getProperty("distance")+1);
					obj.setProperty("fuel_cons",
							(Double)obj.getProperty("fuel_cons")+
							(Double)obj.getProperty("extra_fuel")*(Integer)parameters.get("quantity")
							);
				}
		}
		return null;
	}
	
	public Object getId()
	{
		return "mover";
	}
	
	private boolean walkable(IVector2 newPos, IEnvironmentSpace space) {
		
		Collection estradasSeguintes = ((Grid2D) space).getSpaceObjectsByGridPosition(newPos, "estrada");
		Collection c = ((Grid2D) space).getSpaceObjectsByGridPosition(newPos, "camiao_lixo");
		Collection cv = ((Grid2D) space).getSpaceObjectsByGridPosition(newPos, "camiao_vidro");
		Collection cp = ((Grid2D) space).getSpaceObjectsByGridPosition(newPos, "camiao_papel");
		Collection ce = ((Grid2D) space).getSpaceObjectsByGridPosition(newPos, "camiao_embal");
		return (estradasSeguintes!=null && c==null && cv==null && cp==null && ce==null);
	}
	
}
